import { getCurrentWindow } from '@electron/remote'
// @ts-ignore
import { WebContentsView as RemoteWebContentsView } from '@electron/remote'
// import axios from 'axios'
import type { WebContentsView as WebContentsViewType } from 'electron'
import { capture } from './capture'
const WebContentsView = RemoteWebContentsView as typeof WebContentsViewType

export interface IBrowserContentConfig {
    containerDom: HTMLElement
    initialUrl?: string
    onBackgroundImageSelected?: (message: string) => void
}

export class BrowserContent {
    inited = false
    visible = true
    config: IBrowserContentConfig | null = null
    private webContentsView: InstanceType<typeof WebContentsViewType> | null = null
    // 实例集合
    static instances: BrowserContent[] = []

    constructor() {
        BrowserContent.instances.push(this)
    }

    // 尺寸改变
    handleContainerResize = () => {
        if (!this.webContentsView || !this.config?.containerDom || !this.visible) return
        const { x, y, width, height } = this.config.containerDom.getBoundingClientRect()
        this.webContentsView.setBounds({ x, y, width, height })
    }

    // 初始化
    initBrowserContent(config: IBrowserContentConfig) {
        if (this.inited) return
        this.config = config
        // 创建webContentsView
        this.webContentsView = new WebContentsView({
            webPreferences: {
                nodeIntegration: true,
                contextIsolation: false,
                webSecurity: false
                // enableRemoteModule: true,
                // preload: path.join(__dirname, 'preload.js'),
            }
        })
        if (!this.webContentsView) return
        // 获取当前窗口
        const currentWin = getCurrentWindow()
        // 把contentView添加到当前窗口
        currentWin.contentView.addChildView(this.webContentsView)
        // 设置窗口的大小
        this.handleContainerResize()
        window.addEventListener('resize', this.handleContainerResize)

        // 每次发生加载完成事件后往window里注入onSelectionChanged监听器，选中元素变化时触发
        this.webContentsView.webContents.addListener('did-finish-load', () => {
            console.log('webview did-finish-load')
            // 声明onSelectionChanged函数，此函数会被devtools插件在选中元素时调用
            this.webContentsView?.webContents.executeJavaScript(`
window.onSelectionChanged = () => {
    const el = $0
    const backgroundImage = getComputedStyle(el).backgroundImage
    let src = backgroundImage
    // 是img元素吗
    console.log(el.src)
    if (el.tagName === 'IMG') {
            src = el.src
    }
    console.log('BACKGROUND_IMAGE ' + src)
}
        `)
        })

        // 监听webview的console消息
        this.webContentsView.webContents.addListener('console-message', (_e, _level, originMessage) => {
            console.log('console-message', originMessage)
            if (originMessage.startsWith('BACKGROUND_IMAGE ')) {
                const message = originMessage.replace('BACKGROUND_IMAGE ', '')
                this.config?.onBackgroundImageSelected && this.config?.onBackgroundImageSelected(message)
            }
        })

        // 监听网络请求响应

        capture(this.webContentsView.webContents)

        if (config?.initialUrl) {
            this.loadUrl(config.initialUrl)
            setTimeout(() => {
                this.handleContainerResize()
            }, 0)
        }
    }

    // 获取webContentsView
    getWebContentsView() {
        return this.webContentsView
    }

    // 加载路径
    loadUrl(url: string) {
        this.webContentsView?.webContents?.loadURL(url)
    }

    // 隐藏
    hide() {
        this.visible = false
        this.webContentsView?.setVisible(false)
    }

    // 显示
    show() {
        this.visible = true
        this.webContentsView?.setVisible(true)
        this.handleContainerResize()
    }

    // 销毁
    destroy() {
        // this.webContentsView?.
        // 销毁webContentsView
        window.removeEventListener('resize', this.handleContainerResize)
        // 从数组中删除
        BrowserContent.instances.splice(BrowserContent.instances.indexOf(this), 1)
        if (!this.webContentsView) return
        // 获取当前窗口
        const currentWin = getCurrentWindow()
        // 把contentView添加到当前窗口
        currentWin.contentView.removeChildView(this.webContentsView)
    }
}

// @ts-ignore
window.BrowserContent = BrowserContent
